import httpConfig from "../config/http.config.js";
import Helper from "../utils/helper.js";


const http = {};

http.post = (url, param, loading = true, requireToken = true, encrypt = 0) => {
	return request(url, param, loading, requireToken, 'POST', encrypt)
};
http.get = (url, param, loading, requireToken = true, encrypt = 3) => {
	return request(url, param, loading, requireToken, 'GET', encrypt)
}

let queryTime = {},
	interval = 300;

const request = (url, param, loading, requireToken = true, method = 'POST', encrypt_type = 3) => {
	// 处理防抖节流
	if (!param) param = {};
	if (loading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return new Promise((resolve, reject) => {
		let paramStr = JSON.stringify(param);
		uni.request({
			url: httpConfig.baseUrl + url,
			method,
			data: param,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				if (res.data.code == 1) {
					res.data.data = JSON.parse(data);
				} else if (res.data.code <= -1) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					uni.removeStorageSync('refresh_token');
					uni.redirectTo({
						url: '/pages/login/login'
					})
					reject('登录过期');
					return;
				} else if (res.data.code == 0) {
					// Helper.toast(res.data.msg);
				}
				// console.log(res.data, url, '返回数据');
				resolve(res.data);
			},
			fail: _ => {
				Helper.toast('网络错误');
				uni.navigateTo({
					url: "/pages/noNetwork/noNetwork"
				})
				reject('网络繁忙!');
			},
			complete: _ => {
				if (loading) {
					uni.hideLoading();
				}
			}
		});

	});
}

export default http;